'use client'
import React, { useEffect, useRef, useState } from 'react'
import { usePostSSE } from '@/hooks/usePostSSE'
import Markdown from '@/app/components/markDown'
import Footer from './components/footer'
import SettingPop from './components/setting'
import { SSEStatus, GPTStreamResponse } from '@/types/chat.d'
import useStore from '@/store/index'

export default function ChatSSE() {
  const [status, setStatus] = useState<SSEStatus>('idle')
  const [currentReplyId, setCurrentReplyId] = useState<string | null>(null)
  const [autoScroll, setAutoScroll] = useState(true)

  const chatList = useStore((state) => state.chatList)
  const addSendMsg = useStore((state) => state.addSendMsg)
  const addReceiveMsg = useStore((state) => state.addReceiveMsg)

  const scrollBoxRef = useRef<HTMLDivElement | null>(null)
  const bottomRef = useRef<HTMLDivElement | null>(null)
  const resizeObserverRef = useRef<ResizeObserver | null>(null)
  const settingRef = useRef<{ open: () => void }>(null)
  const { start } = usePostSSE<{ message: string }, GPTStreamResponse>()

  const generateUniqueId = () =>
    Date.now().toString(36) + Math.random().toString(36).slice(2, 10)

  const handleSendMessage = (message: string) => {
    message = message.endsWith('\n') ? message.slice(0, -1) : message
    const msgId = generateUniqueId()
    setAutoScroll(true)
    addSendMsg({
      id: msgId,
      user_id: 1,
      message,
      sender_type: 'user',
    })
    setCurrentReplyId(msgId)

    start({
      url: '/api/chat',
      body: { message },
      onMessage: handleMessage,
    })
  }

  const openSetting = () => {
    settingRef.current?.open()
  }
  const handleMessage = ({
    status,
    data,
  }: {
    status: SSEStatus
    data: GPTStreamResponse
  }) => {
    console.log('我的状态改变', status)

    setStatus(status)
    if (status === 'message') {
      addReceiveMsg({
        id: (currentReplyId || generateUniqueId()) + '1',
        user_id: 1,
        message: data.message,
        sender_type: 'gpt',
      })
    }
  }

  const onScroll = () => {
    const el = scrollBoxRef.current
    if (!el) return
    const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 10 // 容错范围
    setAutoScroll(atBottom)
  }

  // 使用 ResizeObserver 监听 bottomRef 尺寸变更 => 自动滚动
  useEffect(() => {
    const box = scrollBoxRef.current
    const bottom = bottomRef.current
    if (!box || !bottom) return

    if (resizeObserverRef.current) {
      resizeObserverRef.current.disconnect()
    }

    resizeObserverRef.current = new ResizeObserver(() => {
      if (autoScroll) {
        box.scrollTop = box.scrollHeight
      }
    })

    resizeObserverRef.current.observe(bottom)

    return () => {
      resizeObserverRef.current?.disconnect()
    }
  }, [chatList.length, autoScroll])

  return (
    <div className="w-screen h-screen flex flex-col overflow-hidden">
      <div
        ref={scrollBoxRef}
        className="flex-1 overflow-y-auto custom-scrollbar"
        onScroll={onScroll}
      >
        <div className="w-full flex flex-col items-center">
          <div className="w-[200px] h-[10px]" />
          {chatList.map((item, index) => {
            const isUser = item.sender_type === 'user'
            return (
              <div
                key={item.id || index}
                className={`w-full sm:w-11/12 md:w-8/12 lg:w-6/12 xl:w-5/12 max-w-4xl p-4 flex ${
                  isUser ? 'justify-end' : 'justify-start'
                }`}
                ref={index === chatList.length - 1 ? bottomRef : null}
              >
                <div
                  className={`max-w-[97%] rounded-2xl px-4 py-2 text-sm ${
                    isUser ? 'bg-gray-200 text-black' : 'mr-auto '
                  }`}
                >
                  <Markdown content={item.message} />
                </div>
              </div>
            )
          })}
          {status === 'connecting' && (
            <div className="flex flex-row gap-2 w-full sm:w-11/12 md:w-8/12 lg:w-6/12 xl:w-5/12 max-w-4xl pl-5">
              <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce"></div>
              <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:-.3s]"></div>
              <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:-.5s]"></div>
              <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:-.8s]"></div>
            </div>
          )}

          <div className="w-[200px] h-[10px]" />
        </div>
      </div>
      <Footer
        sendStatus={status}
        sendMessage={handleSendMessage}
        openSetting={openSetting}
      />
      <SettingPop ref={settingRef}></SettingPop>
    </div>
  )
}
